#!/bin/bash
# This will download, package and install the latest version of Searx-Qt on
# Debian based systems. To install git development version set SEARXQT_GIT to
# anything but 0.


VERSION="0.3-beta1"
TMP_PATH="/tmp/searx-qt-tmp-build/"
SEARXQT_GIT=${SEARXQT_GIT:=0}


DEP_BUILD="python3-stdeb gettext pyqt5-dev-tools"

if [[ $SEARXQT_GIT -eq 0 ]]; then
	DEP_BUILD+=" wget"
else
	DEP_BUILD+=" git"
fi


# Install dependencies ########################################################

#-- Build dependencies -----------------------------------------
echo "# Install build dependencies:"
sudo apt install $DEP_BUILD

if [[ $? -ne 0 ]]; then
	echo "Failed to install build dependencies."
	exit 1
fi


#-- Run dependencies -------------------------------------------
echo "# Install runtime dependencies:"
sudo apt install python3 python3-requests python3-pyqt5 python3-socks

if [[ $? -ne 0 ]]; then
	echo "Failed to install runtime dependencies."
	exit 1
fi


# Create and cd into tmp dir ##################################################

# -- Delete tmp path --------------------------------------------
if [ -d "$TMP_PATH" ]; then
	rm -rf "$TMP_PATH"
fi

# -- Create tmp path
mkdir "$TMP_PATH"

if [[ $? -ne 0 ]]; then
	echo "Failed to create temporary build path."
	exit 1
fi

cd "$TMP_PATH"


# Download and extract the source #####################################
if [[ $SEARXQT_GIT -eq 0 ]]; then
	wget "https://notabug.org/CYBERDEViL/searx-qt/archive/$VERSION.tar.gz"

	if [[ $? -ne 0 ]]; then
		echo "Failed to download the source."
		exit 1
	fi

	# -- Extract the source -------------------------------------
	tar -xvf "$VERSION.tar.gz"

	if [[ $? -ne 0 ]]; then
		echo "Failed to extract the source."
		exit 1
	fi

	cd searx-qt
else
	git clone "https://notabug.org/CYBERDEViL/searx-qt"

	if [[ $? -ne 0 ]]; then
		echo "Failed to download the source from git."
		exit 1
	fi

	cd searx-qt

	VERSION=$(python -c "from searxqt.version import __version__; print(__version__)")
fi


# Create .deb package #########################################################
./utils/gen_deb.sh

if [[ $? -ne 0 ]]; then
	echo "Failed to create package."
	exit 1
fi


# Install .deb package ########################################################
sudo dpkg -i "./deb_dist/python3-searx-qt_$VERSION-1_all.deb"

if [[ $? -ne 0 ]]; then
	echo "Failed to install package."
	exit 1
fi


# Cleanup #####################################################################
rm -rf "$TMP_PATH"


echo "Searx-Qt $VERSION installed succesfully!"
